<template>
  <div class="animated fadeIn">
    <Row>
      <i-col :span="8">
        <div id="myChartPie" style="width:100%;min-height: 200px;"></div>
      </i-col>
      <i-col :span="8">
        <div id="myChartBar" style="width:100%;min-height: 200px;"></div>
      </i-col>
      <i-col :span="8">
        <div id="myChartLine" style="width:100%;min-height: 200px;"></div>
      </i-col>
    </Row>

    <Row>
      <i-col>
        <Form ref="tabParam" :model="tabParam" label-position="right" inline>
          <FormItem>
            <Button type="primary" @click="exportDataInventory">
              <Icon type="ios-download-outline"></Icon>
              导出原始数据
            </Button>
          </FormItem>
          <FormItem label="到站时间：">
            <DatePicker v-model="timeSlot.timeVal" type="daterange" :options="timeSlot.timeOptions" split-panels
                        placeholder="绑箱时间" format="yyyy年MM月dd日" style="width: 230px">
            </DatePicker>
          </FormItem>
          <FormItem label="车号：">
            <Input type="text" v-model="tabParam.shippingAddress" placeholder="送货地址"></Input>
          </FormItem>
          <FormItem label="车次：">
            <Input type="text" v-model="tabParam.productName" placeholder="品名"></Input>
          </FormItem>
          <FormItem label="装载种类">
            <Select v-model="tabParam.isContainer" placeholder="请选择集装箱种类" style="width: 200px">
              <Option v-for="item in isContainerList" :value="item.isContainer" :key="item.isContainer">{{ item.truckTypeName }}</Option>
            </Select>
          </FormItem>
          <FormItem label="发站：">
            <Input type="text" v-model="tabParam.containerNoBody" placeholder="集装箱号"></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSearch" icon="ios-search">
              搜索
            </Button>
          </FormItem>
        </Form>
        <tablePage ref="orderReportNewTab" :api="orderLiquidationByPage" :param="tabParam">
          <template slot-scope="props">
            <Table :columns="containerColumn" :data="props.data"></Table>
          </template>
        </tablePage>
      </i-col>
    </Row>

    <Row>
      <i-col>
        <template>
          <Checkbox-group v-model="tableColumnsChecked" @on-change="changeTableColumns">
            <Checkbox label="show">Show</Checkbox>
            <Checkbox label="weak">Weak</Checkbox>
            <Checkbox label="signin">Signin</Checkbox>
            <Checkbox label="click">Click</Checkbox>
            <Checkbox label="active">Active</Checkbox>
            <Checkbox label="day7">7, retained</Checkbox>
            <Checkbox label="day30">30, retained</Checkbox>
            <Checkbox label="tomorrow">The next day left</Checkbox>
            <Checkbox label="day">Day Active</Checkbox>
            <Checkbox label="week">Week Active</Checkbox>
            <Checkbox label="month">Month Active</Checkbox>
          </Checkbox-group>
          <Table :data="tableData2" :columns="tableColumns2" border></Table>
        </template>
      </i-col>
    </Row>
  </div>
</template>
<script>
  import echarts from 'echarts'
  import tablePage from '@components/table/tablePage.vue'
  import {orderLiquidationByPage} from '@api/backEnd/report'
  import xlinkModal from '@components/modal/xlinkModal'
  import {getOwnFleet} from '@api/backEnd/station'
  import {exportUtil} from '@/vendor/exportInvoke'
  import {mapGetters} from 'vuex'
  import moment from 'moment'

  export default {
    name: 'index',
    data () {
      let tableData2 = this.mockTableData2()
      let tableColumns2 = []
      let tableColumnsChecked = ['show', 'weak', 'signin', 'click', 'active', 'day7', 'day30', 'tomorrow', 'day', 'week', 'month']
      let addressList = []
      let timeTypes = {
        startTime: 0,
        endTime: 1
      }
      let isContainerList = [
        {'isContainer': '', 'truckTypeName': '全部'},
        {'isContainer': 1, 'truckTypeName': '集装箱'},
        {'isContainer': 0, 'truckTypeName': '整车运输'}
      ]
      let operatModal = {
        trackingShow: false
      }
      let roleType = 1
      let containerStatues = [
        {label: '重箱出场', val: '1'},
        {label: '非重箱出场', val: '0'}
      ]
      let orderStatues = [
        {label: '未到', val: '3,4,5'},
        {label: '已到', val: '1,2'},
        {label: '已完成', val: '6'}
      ]
      let timeSlot = {
        timeOptions: {
          shortcuts: [
            {
              text: '最近一周 ',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              }
            },
            {
              text: '最近一月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              }
            },
            {
              text: '最近三个月',
              value () {
                let end = new Date()
                let start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              }
            }
          ]
        },
        timeVal: [moment().subtract(7, 'days').format('YYYY-MM-DD') + ' 00:00:00', moment().format('YYYY-MM-DD') + ' 00:00:00']
      }
      let trackName = []
      let tabParam = {
        mainOrderNo: '',
        productName: '',
        isContainer: '',
        containerNoBody: '',
        shippingAddress: '',
        trackName: '',
        fleetId: '',
        status: [],
        heavyOrEmpty: containerStatues[0].val,
        bindTimeStart: timeSlot.timeVal[0],
        bindTimeEnd: timeSlot.timeVal[1]
      }
      let containerColumn = [
        {
          title: '车号',
          key: 'main_order_no',
          ellipsis: 'false',
          fixed: 'left',
          width: 200
        },
        {
          title: '当前车次',
          ellipsis: 'false',
          key: 'order_no',
          width: 200
        },
        {
          title: '预计到达时间',
          width: 250,
          sortable: true,
          render: (h, params) => {
            let thisdata = params.row.endStationTime
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '装箱类型',
          ellipsis: 'false',
          key: 'shipper',
          width: 200
        },
        {
          title: '发站',
          ellipsis: 'false',
          key: 'receiver',
          width: 200
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'product_name',
          width: 100
        },
        {
          title: '当前位置',
          ellipsis: 'false',
          key: 'start_station_name',
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 80,
          render: (h, params) => {
            let trackingBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.showTracking(params.row)}>轨迹</i-button>)
            let btnArray = []
            btnArray.push(trackingBtn)
            return (btnArray)
          }
        }
      ]
      let datas = {
        tableData2,
        tableColumns2,
        tableColumnsChecked,
        operatModal,
        isContainerList,
        tabParam,
        containerColumn,
        orderLiquidationByPage,
        containerStatues,
        timeTypes,
        timeSlot,
        addressList,
        trackName,
        roleType,
        orderStatues
      }
      return datas
    },
    methods: {
      drawPie () {
        let myChartPie = echarts.init(document.getElementById('myChartPie'))
        let option = {
          title: {
            text: '某站点用户访问来源',
            subtext: '纯属虚构',
            x: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
          },
          series: [
            {
              name: '访问来源',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: [
                {value: 335, name: '直接访问'},
                {value: 310, name: '邮件营销'},
                {value: 234, name: '联盟广告'},
                {value: 135, name: '视频广告'},
                {value: 1548, name: '搜索引擎'}
              ],
              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        if (option && typeof option === 'object') {
          myChartPie.setOption(option, true)
        }
      },
      drawBar () {
        let myChartBar = echarts.init(document.getElementById('myChartBar'))
        let option = {
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          }]
        }
        if (option && typeof option === 'object') {
          myChartBar.setOption(option, true)
        }
      },
      drawLine () {
        let myChartLine = echarts.init(document.getElementById('myChartLine'))
        let option = {
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line'
          }]
        }
        if (option && typeof option === 'object') {
          myChartLine.setOption(option, true)
        }
      },
      showTracking (row) {
        this.mainOrderCurrentRow = row
        this.operatModal.trackingShow = true
      },
      handleSearch (param) {
        /*  param.pageSize = param.pageSize =
         orderLiquidationByPage(param).then(res => {
         // console.log(this.searchForm + ' --- searchForm')
         if (res.data.isSuccess === 1) {
         this.main_order_list = res.data.data.list
         this.pageTotal = res.data.data.total
         }
         }) */
        this.$refs['orderReportNewTab'].dataRefresh()
      },
      exportDataInventory () {
        let param = Object.assign({}, this.tabParam)
        param.page = 1
        param.pageSize = 100000
        orderLiquidationByPage(param).then(res => {
          if (res.data.isSuccess === 1) {
            let resDate = res.data.data.rows
            // let resColumns = JSON.parse(JSON.stringify(this.stationColumn))
            let result = this.fasetJson(resDate)
            exportUtil.export2Excel('业务报表', result.columns, result.data)
          }
        })
      },
      fasetJson (tabData) {
        let result = {
          columns: [
            {title: '联运单号', key: 'main_order_no'},
            {title: '子单号', key: 'order_no'},
            {title: '货票号', key: 'waybill_no'},
            {title: '集装箱号', key: 'container_no_body'},
            {title: '发货人', key: 'shipper'},
            {title: '收货人', key: 'receiver'},
            {title: '货物名称', key: 'product_name'},
            {title: '发站', key: 'start_station_name'},
            {title: '到站', key: 'end_station_name'},
            {title: '发站时间', key: 'start_station_time'},
            {title: '到站时间', key: 'end_station_time'},
            {title: '子运单状态', key: 'status'},
            {title: '绑箱时间', key: 'bind_time'},
            {title: '司机名称', key: 'driver_name'},
            {title: '车牌号', key: 'truck_plate'},
            {title: '送货地址', key: 'shipping_address'},
            {title: '接取送达费', key: 'zkjf018'}
          ],
          data: []
        }
        let indexCount = 0
        tabData.forEach((item) => {
          if (item.voucher_img && item.fleet_id && item.driver_id) {
            item.status = '已完成'
          } else if (item.fleet_id && item.driver_id && item.shipping_address) {
            item.status = '配送中'
          } else if (item.fleet_id) {
            item.status = '待配送'
          } else if (!item.fleet_id && !item.driver_id) {
            item.status = '待拉运'
          }
          item.container_no_body = item.container_no_head + item.container_no_body
          let dataItem = {
            main_order_no: item.main_order_no,
            order_no: item.order_no,
            waybill_no: item.waybill_no,
            container_no_body: item.container_no_body,
            shipper: item.shipper,
            receiver: item.receiver,
            product_name: item.product_name,
            start_station_name: item.start_station_name,
            end_station_name: item.end_station_name,
            start_station_time: item.start_station_time,
            end_station_time: item.end_station_time,
            status: item.status,
            bind_time: item.bind_time,
            driver_name: item.driver_name,
            truck_plate: item.truck_plate,
            shipping_address: item.shipping_address,
            zkjf018: item.zkjf018
          }
          result.data.push(dataItem)
          indexCount++
        })
        console.log(indexCount)
        return result
      },
      mockTableData2 () {
        let data = []

        function getNum () {
          return Math.floor(Math.random() * 10000 + 1)
        }

        for (let i = 0; i < 10; i++) {
          data.push({
            name: 'Name ' + (i + 1),
            fav: 0,
            show: getNum(),
            weak: getNum(),
            signin: getNum(),
            click: getNum(),
            active: getNum(),
            day7: getNum(),
            day30: getNum(),
            tomorrow: getNum(),
            day: getNum(),
            week: getNum(),
            month: getNum()
          })
        }
        return data
      },
      getTable2Columns () {
        const table2ColumnList = {
          name: {
            title: 'Name',
            key: 'name',
            fixed: 'left',
            width: 200,
            render: (h, params) => {
              const fav = this.tableData2[params.index].fav
              const style = fav === 0 ? {
                cursor: 'pointer'
              } : {
                cursor: 'pointer',
                color: '#f50'
              }
              return h('div', [
                h('Icon', {
                  style: style,
                  props: {
                    type: fav === 0 ? 'ios-star-outline' : 'ios-star'
                  },
                  nativeOn: {
                    click: () => {
                      this.toggleFav(params.index)
                    }
                  }
                }),
                h('span', ' ' + params.row.name)
              ])
            }
          },
          show: {
            title: 'Show',
            key: 'show',
            width: 150,
            sortable: true
          },
          weak: {
            title: 'Weak',
            key: 'weak',
            width: 150,
            sortable: true
          },
          signin: {
            title: 'Signin',
            key: 'signin',
            width: 150,
            sortable: true
          },
          click: {
            title: 'Click',
            key: 'click',
            width: 150,
            sortable: true
          },
          active: {
            title: 'Active',
            key: 'active',
            width: 150,
            sortable: true
          },
          day7: {
            title: '7, retained',
            key: 'day7',
            width: 150,
            sortable: true
          },
          day30: {
            title: '30, retained',
            key: 'day30',
            width: 150,
            sortable: true
          },
          tomorrow: {
            title: 'The next day left',
            key: 'tomorrow',
            width: 150,
            sortable: true
          },
          day: {
            title: 'Day Active',
            key: 'day',
            width: 150,
            sortable: true
          },
          week: {
            title: 'Week Active',
            key: 'week',
            width: 150,
            sortable: true
          },
          month: {
            title: 'Month Active',
            key: 'month',
            width: 150,
            sortable: true
          }
        }
        let data = [table2ColumnList.name]
        this.tableColumnsChecked.forEach(col => data.push(table2ColumnList[col]))
        return data
      },
      changeTableColumns () {
        this.tableColumns2 = this.getTable2Columns()
      },
      toggleFav (index) {
        this.tableData2[index].fav = this.tableData2[index].fav === 0 ? 1 : 0
      }
    },
    watch: {
      // tabParam: {
      //   handler: function (val, oldVal) {
      //     this.$refs['orderReportNewTab'].dataRefresh()
      //   },
      //   deep: true
      // },
      'timeSlot.timeVal': function (val, oldval) {
        if (val && val[0] && val[1]) {
          this.tabParam.bindTimeStart = moment(val[0]).format('YYYY-MM-DD') + ' 00:00:00'
          this.tabParam.bindTimeEnd = moment(val[1]).format('YYYY-MM-DD') + ' 23:59:59'
        } else {
          delete this.tabParam.bindTimeStart
          delete this.tabParam.bindTimeEnd
        }
        // this.$refs['orderReportNewTab'].dataRefresh()
      }
    },
    mounted () {
      this.changeTableColumns()
      this.drawPie()
      this.drawBar()
      this.drawLine()
      if (this.currentUser.role.indexOf('车队') !== -1) {
        this.roleType = 2
      }
      if (this.roleType === 1) {
        getOwnFleet().then(res => {
          if (res.data.isSuccess === 1) {
            this.trackName = res.data.data
          }
        })
      }
    },
    computed: {
      ...mapGetters(['currentUser'])
    },
    components: {tablePage, xlinkModal}
  }
</script>
<style type="text/css" scoped>
</style>
